package com.redribbon.droidnoise;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import android.util.Log;

class NoiseClient // extends Thread
{
	private final String TAG = "CLIENT-NET";
	
	private DatagramSocket socket = null;
	
	NoiseClient()
	{
		try {
			Log.d(TAG, "Port Numbers: (Client, Server) = " + NoiseConstants.client_port_number + ", " + NoiseConstants.server_port_number);
			socket = new DatagramSocket(NoiseConstants.client_port_number);
			socket.setBroadcast(true); // may not need for receiving
			socket.setSoTimeout(NoiseConstants.SOCKET_RECV_TIMEOUT);

		} catch (IOException e) {
			Log.e(TAG, "socket create failed", e);
		}
	}
	
	
	public byte[] getNoise()
	{
		byte[] buf;
		int buflen = 1024; // some buflen in case getReceiveBufferSize doesn't work
		
		try {
			buflen = socket.getReceiveBufferSize();
		} catch (SocketException e) {
			Log.e(TAG, "getReceiveBufferSize failed", e);
		}
		Log.i(TAG, "getReceiveBufferSize = " + buflen);
		buf = new byte[buflen]; // whatever it is
	
		// get data into a buffer until there is no more data (timeout)
		try {
			// for now just get one packet and return
			//while (true) {	
				DatagramPacket packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);
				//String s = new String(packet.getData(), 0, packet.getLength());
				Log.d(TAG, "Received UDP bytes: " + buf.length);
			//}
		} catch (SocketTimeoutException e) {
			Log.d(TAG, "Receive timed out");
			return null; // no data
		} catch (IOException ee) {
			Log.e(TAG, "Receive failed", ee);
			return null;
		} catch (Exception e) {
			Log.e(TAG, "Other exception noise client: ", e);
		}
		
		return buf;
	}
}
